<!DOCTYPE html>
<html lang="en" style="height: 100%">
<head>
  <meta charset="utf-8">
  <title>学生成绩雷达图</title>
  <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
  <style>
    #container { padding: 20px; box-sizing: border-box; }
  </style>
</head>
<body style="height: 100%; margin: 0">
<div id="container" style="height: 100%"></div>
<script src="assets/js/jquery-3.3.1.min.js"></script>
<script src="assets/admin/js/login-interceptor.js"></script>
<script type="text/javascript" src="https://fastly.jsdelivr.net/npm/echarts@5/dist/echarts.min.js"></script>

<script type="text/javascript">
  var dom = document.getElementById('container');
  var myChart = echarts.init(dom, null, {
    renderer: 'canvas',
    useDirtyRect: false
  });

  function loadDataAndRenderChart() {
    axios.get('/score/getAllSubjectsAndMyScores')
            .then(function(response) {
              if (response.data.code === "0") {
                var resultData = response.data.data;
                var allSubjects = resultData.subjects;       // 所有科目
                var myScores = resultData.myScores;          // 个人成绩（修正字段名）
                var allScores = resultData.allScores;        // 全班所有成绩

                // 1. 处理个人成绩（无成绩则为0）
                var myScoreMap = {};
                myScores.forEach(score => {
                  myScoreMap[score.subId] = score.score || 0;
                });

                // 2. 处理班级平均分（按科目分组计算）
                var subjectScoreStats = {}; // 结构: { subId: { total: 总分, count: 人数 } }

                // 初始化所有科目统计数据
                allSubjects.forEach(subject => {
                  subjectScoreStats[subject.id] = { total: 0, count: 0 };
                });

                // 累加所有学生的成绩
                allScores.forEach(score => {
                  const subId = score.subId;
                  if (subjectScoreStats[subId]) {
                    subjectScoreStats[subId].total += (score.score || 0); // 无成绩按0算
                    subjectScoreStats[subId].count += 1;
                  }
                });

                // 3. 提取雷达图数据
                var radarIndicators = [];
                var myScoreValues = [];
                var avgScoreValues = [];

                allSubjects.forEach(subject => {
                  const subId = subject.id;
                  // 科目指标
                  radarIndicators.push({
                    name: subject.name, // 修正科目名称字段（后端Subjects类应为subName）
                    max: 100
                  });
                  // 个人成绩（无则0）
                  myScoreValues.push(myScoreMap[subId] || 0);
                  // 班级平均分（无数据则0）
                  const stats = subjectScoreStats[subId];
                  const avg = stats.count > 0 ? (stats.total / stats.count).toFixed(1) : 0;
                  avgScoreValues.push(Number(avg));
                });

                // 4. 雷达图配置
                var option = {
                  title: {
                    text: '个人成绩 vs 班级平均分(每科只统计有分数的同学)',
                    left: 'center'
                  },
                  tooltip: {
                    trigger: 'item',
                    formatter: params => `${params.name}: ${params.value}分`
                  },
                  legend: {
                    data: ['我的成绩', '班级平均分'],
                    bottom: 10
                  },
                  radar: {
                    indicator: radarIndicators,
                    splitArea: { areaStyle: { color: ['rgba(255,255,255,0.3)', 'rgba(200,200,200,0.3)'] } },
                    axisLine: { lineStyle: { color: '#666' } }
                  },
                  series: [
                    {
                      name: '我的成绩',
                      type: 'radar',
                      symbolSize: 8,
                      lineStyle: { width: 3, color: '#4e79a7' },
                      itemStyle: { color: '#4e79a7' },
                      areaStyle: { color: 'rgba(78, 121, 167, 0.3)' },
                      data: [{ value: myScoreValues, name: '我的成绩' }]
                    },
                    {
                      name: '班级平均分',
                      type: 'radar',
                      symbolSize: 8,
                      lineStyle: { width: 3, color: '#e53935' },
                      itemStyle: { color: '#e53935' },
                      areaStyle: { color: 'rgba(229, 57, 53, 0.2)' },
                      data: [{ value: avgScoreValues, name: '班级平均分' }]
                    }
                  ]
                };

                myChart.setOption(option);
              } else {
                alert('获取数据失败: ' + response.data.msg);
              }
            })
            .catch(error => {
              console.error('请求失败:', error);
              alert('服务器连接失败');
            });
  }

  window.addEventListener('load', loadDataAndRenderChart);
  window.addEventListener('resize', () => myChart.resize());
</script>
</body>
</html>